package dao

import (
	db2 "data_summary/common/db"
	"data_summary/common/models"
	"gorm.io/gorm"
)

type TaskDao struct {
	db *gorm.DB
}

func NewTaskDao(c *gorm.DB) *TaskDao {
	dao := &TaskDao{
		db: c,
	}
	return dao
}

func (c *TaskDao) TableName(suffix string) *TaskDao {
	c.db = c.db.Table("tj_stat_day_order_" + suffix)
	return c
}

// 新增
func (c *TaskDao) Create(v *models.Task) (insertId int, err error) {
	err = c.db.Create(v).Error
	return v.Id, err
}

// 修改
func (c *TaskDao) Update(v *models.Task) (id int, err error) {
	err = c.db.Save(&v).Error
	return v.Id, err
}

// 删除
func (c *TaskDao) Delete(v *models.Task) (id int, err error) {
	err = c.db.Delete(&v).Error
	return v.Id, err
}

func (c *TaskDao) GetList(where map[string]interface{}, order string, page int, pageSize int) (v []models.Task, err error) {
	err = c.db.Where(where).Order(order).Scopes(db2.Paginate(page, pageSize)).Find(&v).Error
	return c.setHostsForTasks(v)
}

func (task *TaskDao) setHostsForTasks(tasks []models.Task) ([]models.Task, error) {
	var err error
	for i, value := range tasks {
		taskHostDetails, err := task.GetHostIdsByTaskId(value.Id)
		if err != nil {
			return nil, err
		}
		tasks[i].Hosts = taskHostDetails
	}

	return tasks, err
}

func (th *TaskDao) GetHostIdsByTaskId(taskId int) ([]models.TaskHostDetail, error) {
	list := make([]models.TaskHostDetail, 0)
	fields := "th.id,th.host_id,h.alias,h.name,h.port"
	err := th.db.Table("tj_task_host th").
		Joins("left join tj_host   h on (th.host_id=h.id)").
		Where("th.task_id = ?", taskId).
		Select(fields).
		Find(&list).Error

	return list, err
}

func (c *TaskDao) GetTask(where map[string]interface{}) (v models.Task, err error) {
	err = c.db.Where(where).Find(&v).Error
	return v, err
}
